package com.qfjy.project.oauth;

import com.qfjy.entity.po.User;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName WeixinMenuOauth
 * @Description TODO
 * @Author guoweixin
 * @Date 2022/12/5
 * @Version 1.0
 */
@RequestMapping("weixinMenu")
@Controller
@Slf4j
public class WeixinMenuOauth {

    /**WeiUser业务逻辑*/
    @Autowired
    private WeiUserService weiUserService;

    /**User业务逻辑*/
    @Autowired
    private UserService userService;

    /**
     * 1 个人中心按钮
     */
    @GetMapping("oauthUser")
    public void oauthUser(HttpServletResponse response) throws Exception {

        String redirect_uri=MenuManager.REAL_URL+"weixinMenu/invokeUser";
        redirect_uri= URLEncoder.encode(redirect_uri,"UTF-8");

        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" +redirect_uri+
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2204" +
                "#wechat_redirect";


        response.sendRedirect(url);
    }
    /**
     * 2、用户同意授权后
     * 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。
     */
    @RequestMapping("invokeUser")
    public String invokeUser(HttpServletRequest request){
        //code作为换取access_token的票据，每次用户授权带上的 code 将不一样，code只能使用一次，5分钟未被使用自动过期。
        String code=request.getParameter("code");
        String state=request.getParameter("state");
        log.info("code={},state={}",code,state);

        //3带着授权码code 去 认证服务器获取access_token   通过 code 换取网页授权access_token
        String authUrl="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +MenuManager.appId+
                "&secret=" +MenuManager.appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        //4、得到accessToken
        JSONObject jsonObject= WeixinUtil.httpRequest(authUrl,"POST",null);
        log.info(jsonObject.toString());

        String accessToken=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");

        //5、带着accessToken和openid [拉取用户信息(需 scope 为 snsapi_userinfo)] 去资源服务器 获取个人信息
        /** 资源服务器
         http：GET（请使用 https 协议）：
         https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
         */

        String resourceUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" +accessToken+
                "&openid=" +openid+
                "&lang=zh_CN";
        //6、请求资源服务器 得到个人信息
        JSONObject jsonObject1=  WeixinUtil.httpRequest(resourceUrl,"GET",null);



        WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);
        if(weiUser==null){
            //收集微信个人信息，添加wei_user表中
             weiUser=new WeiUser();
            weiUser.setOpenid(openid);
            weiUser.setNickname(filterEmoji(jsonObject1.getString("nickname")));
            weiUser.setHeadimgurl(jsonObject1.getString("headimgurl"));
            weiUserService.insertSelective(weiUser);
        }else{
            //当对象不为空，收集过信息，什么都不用做
        }

        User user= userService.selectUserByWid(weiUser.getId());
        if(user==null){
            request.setAttribute("wid",weiUser.getId());
            request.setAttribute("openid",openid);
            return "user/login";
        }else{
            request.setAttribute("user",user);
            return "user/userInfo";
        }
    }


    /**
     * 会议发单 按钮Oauth
     * @param response
     * @throws Exception
     */
    @GetMapping("oauthMeetingPub")
    public void oauthMeetingPub(HttpServletResponse response) throws Exception {

        String redirect_uri=MenuManager.REAL_URL+"weixinMenu/invokeMeetingPub";
        redirect_uri= URLEncoder.encode(redirect_uri,"UTF-8");

        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" +redirect_uri+
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2204" +
                "#wechat_redirect";


        response.sendRedirect(url);
    }
    /**
     * 2、用户同意授权后
     * 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。
     */
    @RequestMapping("invokeMeetingPub")
    public String invokeMeetingPub(HttpServletRequest request){
        //code作为换取access_token的票据，每次用户授权带上的 code 将不一样，code只能使用一次，5分钟未被使用自动过期。
        String code=request.getParameter("code");
        String state=request.getParameter("state");
        log.info("code={},state={}",code,state);

        //3带着授权码code 去 认证服务器获取access_token   通过 code 换取网页授权access_token
        String authUrl="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +MenuManager.appId+
                "&secret=" +MenuManager.appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        //4、得到accessToken
        JSONObject jsonObject= WeixinUtil.httpRequest(authUrl,"POST",null);
        log.info(jsonObject.toString());

        String accessToken=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");

        //5、带着accessToken和openid [拉取用户信息(需 scope 为 snsapi_userinfo)] 去资源服务器 获取个人信息
        /** 资源服务器
         http：GET（请使用 https 协议）：
         https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
         */

        String resourceUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" +accessToken+
                "&openid=" +openid+
                "&lang=zh_CN";
        //6、请求资源服务器 得到个人信息
        JSONObject jsonObject1=  WeixinUtil.httpRequest(resourceUrl,"GET",null);



        WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);
        if(weiUser==null){
            //收集微信个人信息，添加wei_user表中
            weiUser=new WeiUser();
            weiUser.setOpenid(openid);
            weiUser.setNickname(filterEmoji(jsonObject1.getString("nickname")));
            weiUser.setHeadimgurl(jsonObject1.getString("headimgurl"));
            weiUserService.insertSelective(weiUser);
        }else{
            //当对象不为空，收集过信息，什么都不用做
        }

        User user= userService.selectUserByWid(weiUser.getId());
        if(user==null){
            request.setAttribute("wid",weiUser.getId());
            request.setAttribute("openid",openid);
            return "user/login";
        }else{

            if(user.getRid()==1){
                //发单页面
                request.setAttribute("user",user);
                request.setAttribute("uid",user.getId());
                return "meetingPub/addMeetingPub";
            }else {
                //无权限页面
                return "unauth";
            }

        }
    }


    /**
     * 过滤emoji 或者 其他非文字类型的字符
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        if(source != null)
        {
            Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
            Matcher emojiMatcher = emoji.matcher(source);
            if ( emojiMatcher.find())
            {
                source = emojiMatcher.replaceAll("");
            }
        }else{
            source="";
        }
        return source.trim();
    }

}
